package com.hqbzl.chat.handler;

import java.util.Optional;

import com.hqbzl.chat.factory.Factory;
import com.hqbzl.chat.model.ResponseMessage;
import com.hqbzl.chat.model.SendMessage;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@Sharable
public final class SendMessageHandler extends SimpleChannelInboundHandler<SendMessage> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, SendMessage msg) throws Exception {
		String context = msg.getContext();
		String userName = msg.getUserName();
		String targetUser = msg.getTargetUser();
		Channel channel = Factory.session.getChannel(targetUser);
		if (channel != null) {
			SendMessage build = SendMessage.builder().userName(userName).targetUser(targetUser).context(context)
					.build();
			channel.writeAndFlush(build);
		} else {
			ResponseMessage build = ResponseMessage.builder().result(false).msg("target user is no login").build();
			ctx.writeAndFlush(build);
		}
	}
}